/*******************************************************************************
* CSCI321 Major Project 2010 - University of Wollongong                        *
********************************************************************************
* Program:		WeaveEdit                                              *
* Authors:		Simon Allen (Student#: 3457527, Unix: sa655)           *
*			Scott Bellis (Student#: 3479110, Unix: sjb900)         *
*			Jason Benger (Student#: 3454137, Unix: jb960)          *
*			Timothy Newmarch (Student#: 3459263 Unix: tgn336)      *
*			Benjamin Richardson (Student# 3467752, Unix: bjr401)   *
* Supervisor:		Daniel F. Saffioti                                     *
* Modified:		28/10/2010                                             *
* Description:		WeaveEdit is a highly portable collaborative text      *
*			editor and word processor, allowing several users to   *
*			read and edit multiple documents at the same time.     *
*			It is available for Mac OS X, Windows and Linux,       *
*			utilising Nokia's Qt development framework.            *
*******************************************************************************/


#include <QPixmap>
#include <QColorDialog>
#include <QTime>
#include "colourbutton.h"

ColourButton::ColourButton(QWidget *parent, QColor newColour) : QPushButton(parent)
{
	pixmap = QPixmap(size());
	setColour(newColour);

	/*
	 * Set the minimum size, this fixes a bug where shrinking the parent window
	 * doesn't work because this button won't get smaller (because of resizeEvent().)
	 * This also stops the button from recursively getting larger and flipping out
	 * the window manager and crashing the desktop. Remove this and you WILL die.
	 */
	setMinimumWidth(1);
	setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

	connect(this, SIGNAL(clicked()), this, SLOT(selectColour()));
}

void ColourButton::selectColour()
{
	QColor newColour = QColorDialog::getColor(colour, this, tr("Select Colour"));

	if (newColour.isValid())
		setColour(newColour);
}

void ColourButton::setColour(const QColor newColour)
{
	colour = newColour;
	pixmap.fill(colour);
	setIcon(pixmap);
}

/**
  * Sets ColourButton colour to a random one.
  */
void ColourButton::setToRandomColour()
{
	//seed random number gen
	QTime time(0, 0);
	srand(time.secsTo(QTime::currentTime()));

	//choose a default colour - that is decently light and not too saturated
	QColor randomColour;
	int h = rand() % 350;
	int s = rand() % 100 + 50;
	int v = 255 - (qrand() % 50);
	randomColour.setHsv(h,s,v);
	setColour(randomColour);
}

/**
  * Resize the ColourButton colour rectangle to fill the button surface.
  */
void ColourButton::resizeEvent(QResizeEvent *event)
{
	// Create a smaller size then the button or the window manager FLIPS THE HELL OUT.
	QSize iconSize(event->size().width() - 22, this->iconSize().height() - 2);
	pixmap = QPixmap(iconSize);
	pixmap.fill(colour);
	setIconSize(iconSize);
	setIcon(pixmap);
}
